package com.hui.qiniucloud.service.impl;

import com.hui.qiniucloud.entity.AICharacter;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hui.qiniucloud.service.IDoubaoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class DoubaoService implements IDoubaoService {

    private final WebClient webClient;
    private final ObjectMapper objectMapper;

    public DoubaoService() {
        this.webClient = WebClient.builder()
                .baseUrl("https://ark.cn-beijing.volces.com")
                .build();
        this.objectMapper = new ObjectMapper();
    }

    public Flux<String> chatStreamWithCharacter(String message, AICharacter character, List<Map<String, String>> chatHistory) {
        List<Map<String, String>> messages = new ArrayList<>();

        // 添加角色系统提示词
        messages.add(Map.of(
            "role", "system",
            "content", buildSystemPrompt(character)
        ));

        // 添加历史对话
        if (chatHistory != null) {
            messages.addAll(chatHistory);
        }

        // 添加用户当前消息
        messages.add(Map.of(
            "role", "user",
            "content", message
        ));

        Map<String, Object> requestBody = Map.of(
            "model", "doubao-1-5-pro-32k-250115", // 替换为实际的端点ID
            "messages", messages,
            "stream", true,
            "temperature", 0.7,
            "max_tokens", 1000
        );

        Flux<String> authorization = webClient.post()
                .uri("/api/v3/chat/completions")
                .header("Authorization", "Bearer 70def220-00d9-4bef-ae6d-2d822fed2a98") // 替换为实际API Key
                .header("Content-Type", "application/json")
                .bodyValue(requestBody)
                .retrieve()
                .bodyToFlux(String.class)
                .doOnNext(line -> log.info("接收到原始数据: " + line))
                .filter(line -> line.contains("\"delta\"") && line.contains("\"content\""))
                .doOnNext(line -> log.info("过滤后数据: " + line))
                .map(this::extractContentFromSseData)
                .concatWith(Flux.just("[STREAM_COMPLETE]"))
                .doOnComplete(() -> log.info("流式数据传输完成"));
        log.info("chatStreamWithCharacter: " + character.getName() + " " + message+" " + authorization+" " );
        return authorization;
    }

    private String buildSystemPrompt(AICharacter character) {
        StringBuilder prompt = new StringBuilder();
        prompt.append("你现在要扮演").append(character.getName()).append("。");

        if (character.getBackground() != null && !character.getBackground().isEmpty()) {
            prompt.append("\n背景设定：").append(character.getBackground());
        }

        if (character.getPersonality() != null && !character.getPersonality().isEmpty()) {
            prompt.append("\n性格特征：").append(character.getPersonality());
        }

        if (character.getSystemPrompt() != null && !character.getSystemPrompt().isEmpty()) {
            prompt.append("\n").append(character.getSystemPrompt());
        }

        prompt.append("\n请严格按照角色设定进行对话，保持角色的语言风格和行为特征。");

        return prompt.toString();
    }

    private String extractContentFromSseData(String data) {
        try {
            // 打印原始数据用于调试
            log.info("解析数据: " + data);

            // 使用 Jackson 解析 JSON
            JsonNode jsonNode = objectMapper.readTree(data);

            // 检查是否有 choices 数组
            if (jsonNode.has("choices") && jsonNode.get("choices").isArray() && jsonNode.get("choices").size() > 0) {
                JsonNode choice = jsonNode.get("choices").get(0);

                // 检查是否有 delta 对象和 content 字段
                if (choice.has("delta") && choice.get("delta").has("content")) {
                    String content = choice.get("delta").get("content").asText();
                    log.info("提取到内容: [" + content + "]");
                    return content;
                }
            }

            log.info("没有匹配到内容");
            return "";
        } catch (Exception e) {
            log.error("解析数据失败: " + e.getMessage(), e);
            return "";
        }
    }
}